<template>
  <div class="app-container">
    <el-row
      type="flex"
      class="row"
      style="height: 100%"
      justify="space-between"
      :gutter="12"
    >
      <el-col :span="6" style="height: 100%">
        <el-card class="card-wrap">
          <template #header>
            <el-row
              :gutter="10"
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col :span="12">
                <span>标签列表</span>
              </el-col>
              <el-col :span="12">
                <el-input
                  size="small"
                  v-model="keyword"
                  placeholder="输入关键词搜索"
                  clearable
                ></el-input>
              </el-col>
            </el-row>
          </template>
          <el-tree
            ref="treeRef"
            :data="searchList"
            :props="{ label: 'labelName' }"
            :expand-on-click-node="false"
            default-expand-all
            node-key="labelId"
            show-checkbox
            check-on-click-node
            @check-change="handleTreeCheckChange"
          />
        </el-card>
      </el-col>
      <el-col :span="18" style="height: 100%">
        <el-card header="排序与设置" class="card-wrap">
          <label-sort :list="selectedList" @delete-item="handleDelete" />
          <el-button
            style="margin-top: 16px"
            type="primary"
            size="medium"
            @click="finishCommit"
            >提交</el-button
          >
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { fetchLabelList, fetchSkuLabel, saveSkuLabel } from "@/api/product";
import LabelSort from "@/views/pms/sku/components/LabelSort.vue";
import { PAGE_SIZE_ALL } from "@/utils/constant/system";

export default {
  components: { LabelSort },
  props: {
    value: Array,
  },
  data() {
    return {
      list: [],
      selectedList: [],
      keyword: "",
    };
  },
  computed: {
    searchList() {
      return this.keyword
        ? this.list.filter(this.createFilter(this.keyword))
        : this.list;
    },
  },

  created() {
    this.id = this.$route.query.id;
    this.getList();
  },

  methods: {
    getSelectedObjFromList(obj) {
      const { labelId, labelName, labelNote } = obj;
      return {
        labelId,
        labelName,
        labelNote,
        customNote: labelNote,
      };
    },
    getDetail() {
      this.selectedList = [];

      fetchSkuLabel(this.id).then((response) => {
        response.data
          .sort((a, b) => a.sort - b.sort)
          .forEach((item) => {
            this.selectedList.push(this.getSelectedObjFromList(item));
          });
        this.$refs.treeRef.setCheckedKeys(
          this.selectedList.map((item) => item.labelId),
        );
      });
    },
    createFilter(queryString) {
      return (label) => {
        return (
          label.labelName.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },

    getList() {
      fetchLabelList({
        pageNum: 1,
        pageSize: PAGE_SIZE_ALL,
      }).then((response) => {
        this.list = response.data.list.map((item) => {
          const { id, ...rest } = item;
          return {
            labelId: id,
            ...rest,
          };
        });
        this.getDetail();
      });
    },
    handleTreeCheckChange(obj, isSelect) {
      // 判断当前节点是否已经在 selectedList 中
      const index = this.selectedList.findIndex(
        (item) => item.labelId === obj.labelId,
      );

      if (isSelect) {
        // 如果是选中且不存在于 selectedList 中，则添加
        if (index === -1) {
          this.selectedList.push({
            ...this.getSelectedObjFromList(obj),
          });
        }
      } else {
        // 如果是未选中且存在于 selectedList 中，则删除
        if (index !== -1) {
          this.selectedList.splice(index, 1);
        }
      }
    },
    handleDelete(index) {
      this.$refs.treeRef.setChecked(this.selectedList[index].labelId, false);
    },
    handleSave() {
      this.$emit("finishCommit", this.selectedList);
    },
    finishCommit() {
      this.$confirm("是否要提交该标签列表？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const uploadValue = this.selectedList.map((item, index) => ({
          labelId: item.labelId,
          labelName: item.labelName,
          labelNote: item.customNote,
          sort: index + 1,
        }));
        saveSkuLabel({ labelRelList: uploadValue, skuId: this.id }).then(() => {
          this.$message({
            type: "success",
            message: "提交成功",
            duration: 1000,
          });
          this.$router.back();
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  box-sizing: border-box;
  height: calc((100vh - 50px) / 0.95);

  .row {
    height: 100%;
  }

  .card-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    /deep/ .el-card__body {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
